package com.neusoft.yiyang.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.yiyang.common.entity.bed.Bed;
import com.neusoft.yiyang.common.entity.bed.BedUsage;
import com.neusoft.yiyang.common.entity.customer.Customer;
import com.neusoft.yiyang.common.entity.customer.LeaveRequest;
import com.neusoft.yiyang.common.entity.customer.OutingRequest;
import com.neusoft.yiyang.common.entity.user.User;
import com.neusoft.yiyang.common.enums.BedStatus;
import com.neusoft.yiyang.customer.client.BedClient;
import com.neusoft.yiyang.customer.client.BedUsageClient;
import com.neusoft.yiyang.customer.client.UserClient;
import com.neusoft.yiyang.customer.mapper.CustomerMapper;
import com.neusoft.yiyang.customer.mapper.OutingRequestMapper;
import com.neusoft.yiyang.customer.service.OutingService;
import com.neusoft.yiyang.common.enums.ApprovalStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OutingServiceImpl implements OutingService {

    @Autowired
    private OutingRequestMapper outingRequestMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private UserClient userClient;
    @Autowired
    private BedClient bedClient;
    @Autowired
    private BedUsageClient bedUsageClient;

    @Override
    public Map<String, Object> createOutingRequest(OutingRequest outingRequest) {
        Map<String, Object> result = new HashMap<>();

        // 使用QueryWrapper查询customer_id相同且状态为pending的记录
        QueryWrapper<OutingRequest> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", outingRequest.getCustomerId())
                .eq("approval_status", ApprovalStatus.pending);

        List<OutingRequest> pendingRequests = outingRequestMapper.selectList(queryWrapper);
        if (!pendingRequests.isEmpty()) {
            // 存在重复记录，返回错误信息和已有记录ID
            result.put("success", false);
            result.put("message", "您已有待审批的外出申请，请勿重复提交");
            return result;
        }

        outingRequest.setApprovalStatus(ApprovalStatus.pending);
        outingRequestMapper.insert(outingRequest);
        result.put("success", true);
        result.put("message", "外出申请提交成功");
        return result;
    }

    @Override
    public List<Map<String, Object>> getAllOutingRequests() {
        List<OutingRequest> outingRequests = outingRequestMapper.selectList(null);
        System.out.println(outingRequests);
        List<Map<String, Object>> result = new ArrayList<>();
        for (OutingRequest request : outingRequests) {
            Customer customer = customerMapper.selectById(request.getCustomerId());
            User user = userClient.getUserById(request.getCaretakerId());
            BedUsage bedUsage = bedUsageClient.getBedusageByCid(request.getCustomerId());
            Bed bed = bedClient.getBed(bedUsage.getBedId());
            Map<String, Object> map = new HashMap<>();
            map.put("outingRequest", request);
            map.put("customerName", customer != null ? customer.getCustomerName() : null);
            map.put("caretakerName", user != null ? user.getName() : null);
            map.put("buildingNo", bed != null ? bed.getBuildingNo() : null);
            map.put("floor", bed != null ? bed.getFloor() : null);
            map.put("roomNumber", bed != null ? bed.getRoomNumber() : null);
            map.put("bedNo", bed != null ? bed.getBedNo() : null);
            result.add(map);
        }
        return result;
    }

    @Override
    public List<Map<String, Object>> getOutingRequestsByCaretakerId(Integer caretakerId) {
        QueryWrapper<OutingRequest> qw = new QueryWrapper<>();
        qw.eq("caretaker_id",caretakerId);
        List<OutingRequest> outingRequests = outingRequestMapper.selectList(qw);
        List<Map<String, Object>> result = new ArrayList<>();
        for (OutingRequest outingRequest : outingRequests) {
            Customer customer = customerMapper.selectById(outingRequest.getCustomerId());
            Map<String, Object> map = new HashMap<>();
            map.put("customer", customer);
            map.put("outingRequest",outingRequest);
            result.add(map);
        }
        return result;
    }

    @Override
    public OutingRequest getOutingRequestById(Integer outingRequestId) {
        return outingRequestMapper.selectById(outingRequestId);
    }

    @Override
    public void updateOutingRequestStatus(Integer outingRequestId, String status) {
        OutingRequest outingRequest = outingRequestMapper.selectById(outingRequestId);
        if (outingRequest != null) {
            // 将String类型的status转换为ApprovalStatus枚举类型
            outingRequest.setApprovalStatus(ApprovalStatus.valueOf(status));  // 转换
            outingRequestMapper.updateById(outingRequest);
        }
    }

    @Override
    public void rejectOutingRequest(Integer outingRequestId) {
        OutingRequest outingRequest = outingRequestMapper.selectById(outingRequestId);
        outingRequest.setApprovalStatus(ApprovalStatus.rejected);

        outingRequest.setApprovalTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
        outingRequestMapper.updateById(outingRequest);
    }

    @Override
    public void agreeOutingRequest(Integer outingRequestId) {
        OutingRequest outingRequest = outingRequestMapper.selectById(outingRequestId);
//        Customer customer = customerMapper.selectById(outingRequest.getCustomerId());
//        Bed bed = bedClient.getBed(customer.getBedId());
//        bed.setStatus(BedStatus.out);
//        bedClient.updateBed(bed);
        outingRequest.setApprovalStatus(ApprovalStatus.approved);
        outingRequest.setApprovalTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
        outingRequestMapper.updateById(outingRequest);
    }
    @Override
    public List<Map<String, Object>> searchByCustomerName(String customerName) {
        // 1. 模糊查询所有匹配客户
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.like("customer_name", customerName);
        List<Customer> matchedCustomers = customerMapper.selectList(wrapper);

        if (matchedCustomers.isEmpty()) return new ArrayList<>();

        // 2. 获取所有匹配的 customerId
        List<Integer> customerIds = matchedCustomers.stream()
                .map(Customer::getCustomerId)
                .collect(Collectors.toList());

        // 3. 查找所有对应的 OutingRequest
        QueryWrapper<OutingRequest> lrWrapper = new QueryWrapper<>();
        lrWrapper.in("customer_id", customerIds);
        List<OutingRequest> outingRequests = outingRequestMapper.selectList(lrWrapper);

        List<Map<String, Object>> result = new ArrayList<>();

        for (OutingRequest request : outingRequests) {
            Customer customer = matchedCustomers.stream()
                    .filter(c -> c.getCustomerId().equals(request.getCustomerId()))
                    .findFirst().orElse(null);
            User user = userClient.getUserById(request.getCaretakerId());
            Bed bed = bedClient.getBed(customer.getBedId());
            Map<String, Object> map = new HashMap<>();
            map.put("outingRequest", request);
            map.put("customerName", customer != null ? customer.getCustomerName() : null);
            map.put("userName", user != null ? user.getUsername() : null);
            map.put("buildingNo", bed != null ? bed.getBuildingNo() : null);
            map.put("floor", bed != null ? bed.getFloor() : null);
            map.put("roomNumber", bed != null ? bed.getRoomNumber() : null);
            map.put("bedNo", bed != null ? bed.getBedNo() : null);
            result.add(map);
        }
        return result;
    }

    @Override
    public void returnOutingRequest(Integer outingRequestId, Date actualReturnTime){
        OutingRequest outingRequest = outingRequestMapper.selectById(outingRequestId);
        Customer customer = customerMapper.selectById(outingRequest.getCustomerId());

        Bed bed = bedClient.getBed(customer.getBedId());
        bed.setStatus(BedStatus.occupied);
        bedClient.updateBed(bed);
        outingRequest.setActualReturnTime(actualReturnTime);
        outingRequestMapper.updateById(outingRequest);
    }

    //删除外出申请
    @Override
    public void deleteOutingRequest(Integer outingRequestId) {
        outingRequestMapper.deleteById(outingRequestId);
    }

    //修改外出申请
    @Override
    public void updateOutingRequest(Integer outingRequestId, OutingRequest updateRequest){
        OutingRequest existOutingRequest = outingRequestMapper.selectById(outingRequestId);
        existOutingRequest.setReason(updateRequest.getReason());
        existOutingRequest.setOutingTime(updateRequest.getOutingTime());
        existOutingRequest.setExpectedReturnTime(updateRequest.getExpectedReturnTime());
        outingRequestMapper.updateById(existOutingRequest);
    }

    @Override
    public void confirmOut(Integer outingRequestId) {
        OutingRequest outingRequest = outingRequestMapper.selectById(outingRequestId);
        Customer customer = customerMapper.selectById(outingRequest.getCustomerId());
        Bed bed = bedClient.getBed(customer.getBedId());
        bed.setStatus(BedStatus.out);
        bedClient.updateBed(bed);
        outingRequest.setActualOutTime(new Date());
        outingRequestMapper.updateById(outingRequest);
    }
}
